using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Controls;
using System.Diagnostics;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;

namespace WikiApp.Pages
{
    public class CategoryConfig
    {
        public string Type { get; set; } = string.Empty;
        public string Title { get; set; } = string.Empty;
        public List<CategoryItemConfig> Items { get; set; } = new();
    }

    public class CategoryItemConfig
    {
        public string Title { get; set; } = string.Empty;
        public string Description { get; set; } = string.Empty;
        public string YamlFile { get; set; } = string.Empty;
    }

    public class PagesConfig
    {
        public List<CategoryConfig> Categories { get; set; } = new();
    }

    public static class CategoryPageFactory
    {
        private static PagesConfig? _config;

        public static void Initialize()
        {
            try
            {
                Debug.WriteLine("CategoryPageFactory.Initialize() 开始");
                
                // 使用应用程序的基目录
                var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
                Debug.WriteLine($"应用程序基目录: {baseDirectory}");
                
                var configPath = Path.Combine(baseDirectory, "Config", "pages.yaml");
                Debug.WriteLine($"配置文件路径: {configPath}");

                if (!File.Exists(configPath))
                {
                    // 尝试在当前目录查找
                    configPath = Path.Combine(Directory.GetCurrentDirectory(), "Config", "pages.yaml");
                    Debug.WriteLine($"尝试当前目录配置文件路径: {configPath}");
                    
                    if (!File.Exists(configPath))
                    {
                        var error = $"找不到配置文件: {configPath}";
                        Debug.WriteLine(error);
                        throw new FileNotFoundException(error);
                    }
                }

                Debug.WriteLine("读取配置文件...");
                var yaml = File.ReadAllText(configPath);
                Debug.WriteLine($"配置文件内容:\n{yaml}");

                var deserializer = new DeserializerBuilder()
                    .WithNamingConvention(CamelCaseNamingConvention.Instance)
                    .Build();
                
                _config = deserializer.Deserialize<PagesConfig>(yaml);
                
                if (_config == null)
                {
                    throw new InvalidOperationException("配置文件解析失败，返回null");
                }
                
                if (_config.Categories == null || _config.Categories.Count == 0)
                {
                    throw new InvalidOperationException("配置文件中没有找到任何类别");
                }

                Debug.WriteLine($"配置文件解析完成，包含 {_config.Categories.Count} 个类别");
                foreach (var cat in _config.Categories)
                {
                    Debug.WriteLine($"- Type: {cat.Type}, Title: {cat.Title}");
                }
                
                Debug.WriteLine("CategoryPageFactory.Initialize() 完成");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"初始化失败: {ex.Message}\n{ex.StackTrace}");
                throw;
            }
        }

        public static Page CreatePage(string type)
        {
            try
            {
                Debug.WriteLine($"CategoryPageFactory.CreatePage() 开始，类型: {type}");
                
                if (_config == null)
                {
                    var error = "CategoryPageFactory not initialized. Call Initialize() first.";
                    Debug.WriteLine(error);
                    throw new InvalidOperationException(error);
                }

                Debug.WriteLine($"当前配置中的类别:");
                foreach (var cat in _config.Categories)
                {
                    Debug.WriteLine($"- Type: {cat.Type}, Title: {cat.Title}");
                }

                // 使用不区分大小写的比较
                var category = _config.Categories.Find(c => 
                    string.Equals(c.Type, type, StringComparison.OrdinalIgnoreCase));
                
                if (category == null)
                {
                    var error = $"找不到类型 {type} 的类别配置";
                    Debug.WriteLine(error);
                    throw new ArgumentException(error);
                }

                Debug.WriteLine($"创建页面: {category.Title}");
                var page = new CategoryPage(category.Title, category.Type);
                
                Debug.WriteLine("添加类别项目...");
                foreach (var item in category.Items)
                {
                    Debug.WriteLine($"添加项目: {item.Title}");
                    ((ICategoryPage)page).AddItem(item.Title, item.Description, item.YamlFile);
                }

                Debug.WriteLine("CategoryPageFactory.CreatePage() 完成");
                return page;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"创建页面失败: {ex.Message}\n{ex.StackTrace}");
                throw;
            }
        }
    }
} 